package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        //1.获取当前登录用户
        //Employee employee = (Employee) request.getSession().getAttribute(UserContext.USER_IN_SESSION);
        Employee employee = UserContext.getCurrentUser();
        //2.判断用户是否为超管
        if (employee.isAdmin()) {
            //是==>放行
            return true;
        }
        //否==>进行下一步3
        //3.获取请求的目标方法,(handler是spring mvc 拦截器的请求方法,返回类型是Object,此处需要强转)
        HandlerMethod Method = (HandlerMethod) handler;
        //4判断是否需要权限访问,即有无贴自定义注解
        RequiredPermission annotatio = Method.getMethodAnnotation(RequiredPermission.class);
        if (annotatio == null) {
            //否==>放行
            return true;
        }
        //是==>下一步5
        //5.获取目标方法的权限表达式
        String expression = annotatio.expression();
        //6.获取当前用户的权限方法结果集
        //List<String> list =(List<String>) request.getSession().getAttribute(UserContext.EXPRESSION_IN_SESSION);
        List<String> list = UserContext.getExpression();
        //判断是否包含目标方法的权限表达式
        //是==>放行

        if (list.contains(expression)) {
            return  true;
        }
        //否==>进入错误提示界面
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        return false;
    }
}
